import React, { Suspense, useEffect, useCallback, useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { Provider, useDispatch, useSelector } from 'react-redux';
import { ConfigProvider, Spin, message } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import store, { checkAuthState as checkLocalStorage } from './store';
import PrivateRoute from './components/PrivateRoute';
import Layout from './components/Layout';
import Login from './pages/Login';
import Register from './pages/Register';
import Dashboard from './pages/Dashboard';
import SignIn from './pages/SignIn';
import History from './pages/History';
import { checkAuthState, getUserInfo } from './store/slices/authSlice';

// Import global styles
import './index.css';
import './App.css';

// Configure Antd theme
const theme = {
  token: {
    colorPrimary: '#1890ff',
    borderRadius: 6,
  },
};

// 认证状态检查组件
const AuthStateChecker = ({ children }) => {
  const dispatch = useDispatch();
  const { isAuthenticated, token, user, error } = useSelector(state => state.auth);
  const [userInfoFetched, setUserInfoFetched] = useState(false);
  const [authCheckDone, setAuthCheckDone] = useState(false);
  const [fetchAttempts, setFetchAttempts] = useState(0);
  const MAX_FETCH_ATTEMPTS = 1; // 最大重试次数，减少到1次
  
  // 使用useRef来跟踪组件是否已挂载，避免在组件卸载后设置状态
  const isMounted = React.useRef(false);
  const authCheckRef = React.useRef(false);
  const userInfoRef = React.useRef(false);
  
  // 组件挂载和卸载时设置标志
  useEffect(() => {
    isMounted.current = true;
    return () => {
      isMounted.current = false;
    };
  }, []);

  // 初始化认证状态 - 添加防止无限循环的保护措施
  useEffect(() => {
    // 只在组件挂载后且认证状态未初始化时执行一次
    if (!authCheckRef.current && isMounted.current) {
      console.log('初始化认证状态检查');
      authCheckRef.current = true;
      
      // 检查本地存储中的认证状态
      const localAuthState = checkLocalStorage();
      
      // 确保Redux状态与localStorage同步
      dispatch(checkAuthState());
      
      // 只有在组件仍然挂载时才更新状态
      if (isMounted.current) {
        setAuthCheckDone(true);
      }
    }
  }, [dispatch]);

  // 单独处理用户信息获取，添加防止无限循环的保护措施
  useEffect(() => {
    // 只有当组件已挂载、token存在、用户信息不存在、尚未获取且尝试次数未超过上限时，才获取用户信息
    if (isMounted.current && token && !user && !userInfoRef.current && fetchAttempts < MAX_FETCH_ATTEMPTS) {
      console.log(`尝试获取用户信息，尝试次数: ${fetchAttempts + 1}`);
      
      // 先更新状态，防止重复请求
      setFetchAttempts(prev => prev + 1);
      userInfoRef.current = true;
      
      // 使用setTimeout来确保状态更新已完成
      setTimeout(() => {
        if (isMounted.current) {
          dispatch(getUserInfo())
            .unwrap()
            .then(() => {
              console.log('用户信息获取成功');
            })
            .catch((err) => {
              console.error('获取用户信息失败:', err);
              if (err.status === 401) {
                message.error('认证已过期，请重新登录');
              }
            });
        }
      }, 100);
    }
  }, [token, user, dispatch, fetchAttempts]);

  // 如果认证出错，记录错误但不重置状态
  useEffect(() => {
    if (error && error.includes('认证')) {
      console.error('认证错误:', error);
    }
  }, [error]);

  return <>{children}</>;
};

function AppContent() {
  return (
    <AuthStateChecker>
      <Suspense fallback={<div className="app-loading"><Spin size="large" /></div>}>
        <Router>
          <Routes>
            <Route path="/login" element={<Login />} />
            <Route path="/register" element={<Register />} />
            <Route path="/" element={<PrivateRoute><Layout /></PrivateRoute>}>
              <Route index element={<Navigate to="/dashboard" replace />} />
              <Route path="dashboard" element={<Dashboard />} />
              <Route path="signin" element={<SignIn />} />
              <Route path="history" element={<History />} />
            </Route>
            <Route path="*" element={<Navigate to="/" replace />} />
          </Routes>
        </Router>
      </Suspense>
    </AuthStateChecker>
  );
}

function App() {
  return (
    <Provider store={store}>
      <ConfigProvider locale={zhCN} theme={theme}>
        <AppContent />
      </ConfigProvider>
    </Provider>
  );
}

export default App;
